var UsableProxyPool = require("../service/UsableProxyPool.js");
var Server2Proxy = require('../service/Server2Proxy.js');
var ProxyInfo = require("../common/ProxyInfo.js");
var App = require("../common/App.js");


/**
* 添加到可用池中
*/
exports.add = function(req, res){
	try{
		var p = req.query.proxy;
		var serverIp = req.query.server_ip;
        if(!App.hasServer(serverIp)){
            throw new Error("ServerIp:"+serverIp+" not defined");
        }
		p = JSON.parse(p);
		var proxy = new ProxyInfo(p);
		UsableProxyPool.add(proxy);
		Server2Proxy.add(proxy,serverIp);

		res.send(App.sendSuccess());
	}catch (e){
		res.send(App.sendFail(e));
	}
};

/**
* 从池中删除
*/
exports.del = function(req, res){
	try{
		var p = req.query.proxy;
		p = JSON.parse(p);
		var proxy = new ProxyInfo(p);
		UsableProxyPool.del(proxy);
		Server2Proxy.del(proxy);

		res.send(App.sendSuccess());
	}catch (e){
		res.send(App.sendFail(e));
	}				
};

/**
* 返回指定地区最优的一个代理，并更新代理的优先级
*/
exports.getbest = function(req, res){
    var regionId = req.query.region_id;
	var proxy = UsableProxyPool.get(regionId);
    res.send(App.send(proxy));
};

/**
 * 返回指定地区最优的一个代理，并更新代理的优先级
 */
exports.getbestAndExclude = function(req, res){
    try{
        var regionId = req.query.region_id;
        var p = req.query.proxy;
        pp = JSON.parse(p);

        var proxy = new ProxyInfo(pp);
        console.log(proxy);

        var proxy = UsableProxyPool.getAndExclude(regionId,proxy);
        res.send(App.send(proxy));

    }catch (e){
        res.send(App.sendFail(e));
    }

};

/**
 * 代理请求网络失败是，需要对代理降级
 * @param req
 * @param res
 */
exports.fail = function(req, res){
    try{
        var p = req.query.proxy;
        pp = JSON.parse(p);

        var proxy = new ProxyInfo(pp);

        UsableProxyPool.fail(proxy);
        res.send(App.sendSuccess());
    }catch (e){
        res.send(App.sendFail(e));
    }
}

/**
* 释放代理，并更新代理的优先级
*/
exports.release = function(req, res){
	try{
		var p = req.query.proxy;
		p = JSON.parse(p);
		console.log(p);
		var proxy = new ProxyInfo(p);
		UsableProxyPool.release(proxy);

		res.send(App.sendSuccess());
	}catch (e){
		res.send(App.sendFail(e));
	}					
};

exports.releaseForUserid = function(req, res){
	var userid = req.query.userid;
	UsableProxyPool.releaseForUserid(userid);
	res.send(App.sendSuccess());
}

/**
* 获取所有代理,不更改优先级
*/
exports.all = function(req, res){
    var result = {};
	result.pool = UsableProxyPool.getList();
    result.s2plist = Server2Proxy.getAllList();
    res.send(App.send(result));
};


